package com.taotao.netty.bytebuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: Netty ByteBuf测试
 * @Author: TaoJF
 * @Date: Created in 2018/7/23 下午2:59
 */
public class ByteBufTest {

    private ByteBuf byteBuf;

    @Test
    public void test1() {
        byteBuf = Unpooled.copiedBuffer("hello world", CharsetUtil.UTF_8);
        if (byteBuf.hasArray()) {
            byte[] bytes = byteBuf.array();
            System.out.println(new String(bytes, CharsetUtil.UTF_8));

            System.out.println(byteBuf);
            printByteBufMsg();

            int length = byteBuf.readableBytes();
            System.out.println("当前可以读的长度：" + length);

            for (int i = 0; i < length; i++) {
                System.out.print((char) byteBuf.getByte(i));
            }
            printByteBufMsg();

            for (int i = 0; i < 7; i++) {
                System.out.print((char) byteBuf.readByte());
            }
            printByteBufMsg();


            byteBuf.writeBytes("good good study, day day up".getBytes());
            printByteBufMsg();

            //byteBuf.clear();
            //printByteBufMsg();
            //System.out.print((char) byteBuf.readByte());
            byteBuf.markReaderIndex();
            System.out.println((char) byteBuf.readByte());
            printByteBufMsg();

            byteBuf.resetReaderIndex();
            System.out.println((char) byteBuf.readByte());
            printByteBufMsg();

        }


    }

    private void printByteBufMsg() {
        System.out.println();
        System.out.println("--->> arrayOffset:" + byteBuf.arrayOffset() + " ,readerIndex:" + byteBuf.readerIndex() +
                " ,writerIndex:" + byteBuf.writerIndex() + " ,capacity:" + byteBuf.capacity());
        System.out.println();
    }


    private static int addNums(int num) {
        List<Integer> list = new ArrayList<>();

        int totalNum = 0;
        int n = num;

        while (n > 0) {
            int j = n % 10;
            n = n / 10;
            list.add(j);
        }
        for (int k : list) {
            totalNum += k;
        }
        if (totalNum / 10 > 0) {
            totalNum = addNums(totalNum);
        }
        return totalNum;
    }

    public static void main(String[] args) {
        System.out.println(addNums(255));
    }



}






















